package com.firesys.rounting.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.firesys.R;
import com.firesys.dbhelper.DbTableName;
import com.firesys.dbhelper.SharedPreferenceUtil;
import com.firesys.dbhelper.XmlNameHelper;
import com.firesys.httpserver.DownloadItem;
import com.firesys.httpserver.DownloadManager;
import com.firesys.httpserver.HttpClientServer;
import com.firesys.httpserver.RequestUrl;
import com.firesys.povo.DeviceList;
import com.firesys.rounting.Adapter.MyListAdapter;
import com.firesys.rounting.db.DeviceRoutingDao;
import com.firesys.util.DateUtil;


import android.app.Activity;
import android.app.Dialog;

import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 设备任务管理
 * @author Administrator
 *
 */
public class DeviceTaskActivity extends Activity implements OnClickListener{
	
	    public static final int REQUEST_CODE_ROUTING=1;//巡检代码
	    public static final int REQUEST_CODE_QUERY=2;//查询代码 
	    public static final int REQUEST_CODE_UPLOAD=3;	//上传代码 
	
	    //分组实现收缩组件
		public ExpandableListView mExpandableListView;
		
		public Button button;//更新数据
		
		public DeviceRoutingDao   dao;
		
		public SharedPreferenceUtil  sp;
		
		public int listtotal=0;//表册数
		public int error=0;
		public int total=0;
		public DownloadManager  downma;
	    public ProgressDialog pd;
	    public final static int DIALOG = 1;
		
		public List<DeviceList> list;//设备册信息
		public TextView  textview;
		

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.device_list_info);
		sp=new SharedPreferenceUtil(this);
		dao=new DeviceRoutingDao(this, sp.getValue(XmlNameHelper.SqliteName));
		textview=(TextView)findViewById(R.id.device_list_info_textView1);
		mExpandableListView=(ExpandableListView)findViewById(R.id.device_list_info_expandableListView);
		updateUi();
		button=(Button)findViewById(R.id.device_list_info_download);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				click_upload(v);
				
			}
		});
		
	}

	
	public void updateUi(){
      String update=sp.getValue(XmlNameHelper.rounting_update_date);
		
		
		list=dao.queryAllDeviceList(null);
		if(list.size()==0&&TextUtils.isEmpty(update)){
			textview.setText("当前还未更新过数据");
		}else if(list.size()==0&&!TextUtils.isEmpty(update)){
			textview.setText("当前没有数据，最近更新时间:"+update);
		}else{
			textview.setText("最近更新时间:"+update);
			mExpandableListView.setAdapter(new MyListAdapter(this, list,this));
		}

	}
	
	//下载数据
	public void click_upload(View v){
		
		   showDialog(DIALOG+1);
	}
	
	   @Override
	      protected Dialog onCreateDialog(int id) {
	  	Dialog dialog = null;
	  	switch (id) {
	  	
	  	case DIALOG + 1:
	  	    Builder builder1 = new android.app.AlertDialog.Builder(this);
	  	    // 设置对话框的图标
	  	  
	  	    builder1.setMessage("确定更新新设备册？");
	  	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

	  		@Override
	  		public void onClick(DialogInterface dialog, int which) {
	  		  
	  		     pd=new ProgressDialog(DeviceTaskActivity.this);
	  		    download down=new download(pd);
	  		    down.execute(RequestUrl.DOWNLOAD_ROUNTING_DEVICE);
	  		}
	  	    });
	  	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

	  		@Override
	  		public void onClick(DialogInterface dialog, int which) {

	  		}
	  	    });
	  	    // 创建一个单选按钮对话框
	  	    dialog = builder1.create();
	  	    break;

	  
	  	}

	  	return dialog;
	      }
	      
	
	  public class download extends AsyncTask<String, Integer, String> {

		  	public HttpClientServer server;

		  	public ProgressDialog dialog;
		  	
		  	public int watertotal=0;
		  	


		  	public download(ProgressDialog dialog) {
		  	    this.dialog = dialog;
		  	}

		  	@Override
		  	protected String doInBackground(String... params) {

		  	    String userid = sp.getValue(XmlNameHelper.IMEI);
		  	  String[]  ss=new String[]{"普通闸阀","蝶阀","消火栓","弹性坐封阀","排气阀","","预留堵板","消火栓和弹性阀"};//设备类型
		  	  String[]  ss1=new String[]{"未知","关","1/4开","半开","3/4开","开"};//设备开户状态
		  	 
		  	    Map<String, String> map = new HashMap<String, String>();
		  	    map.put("imei", sp.getValue(XmlNameHelper.IMEI));
		  	    map.put("cpId", sp.getValue(XmlNameHelper.userID));
		  	    System.out.println("----hppt------------"+params[0]);
		  	 String response = server.doPost(map, params[0],true);
		  	 //   String response=getFromAssets();
		  	    System.out.println("response------------"+response);
		  	            //设备册
				    List<ContentValues> devicelist=new ArrayList<ContentValues>();
				    //设备信息
				    List<ContentValues> devicevo=new ArrayList<ContentValues>();		    
				    //图文信息
				    List<ContentValues> tuwen=new ArrayList<ContentValues>();
		  	    if (!response.equals("error")) {
		  		   dao.delectDeviceAll("1");
		  		try {
		  		    JSONObject json=new JSONObject(response);
		  		    JSONArray devicelistjson=json.getJSONArray("lists");
		 		   		  
		  		    total=watertotal=0;
		  		 
		  		    for(int i=0;i<devicelistjson.length();i++){
		  			JSONObject jb=devicelistjson.getJSONObject(i);
		  			String devicelistid=jb.getString("id");
		  			String deviceitem=abc(jb.getString("set"));
		  			
		  			ContentValues  value =new ContentValues();
		  			value.put("devicelistid",devicelistid);
		  			
		  			//value.put("number", jb.getString("deviceListNumber"));
		  			value.put("name", jb.getString("listName"));
		  			value.put("deviceitem",deviceitem);
		  			String type=jb.getString("periodType");
		  			value.put("startdate", jb.getString("startDate"));
		  			value.put("enddate", jb.getString("endDate"));
		  			value.put("total", jb.getInt("valveTotal"));
		  			value.put("operationtype",type);
		  			devicelist.add(value);
		  			JSONArray  devicejson=jb.getJSONArray("valves");
		  			
		  			//添加设备
		  			for(int k=0;k<devicejson.length();k++){
		  			    watertotal++;
		  			    JSONObject  devicejb=devicejson.getJSONObject(k);
		  			  ContentValues devicevalue=new ContentValues();
		  			devicevalue.put("deviceid", devicejb.getString("id"));//设备ID
		  			devicevalue.put("iscopystatus", "0");
		    			devicevalue.put("devicelistid", devicelistid);//所属设备册
		    			devicevalue.put("devicecaliber", devicejb.getString("nd"));//公称通径
		    			devicevalue.put("devicePressure", devicejb.getString("pn"));//公称压车
		    		//	devicevalue.put("inspectionCycle", devicejb.getString("inspectionCycle"));
		    		//	devicevalue.put("maintenanceCycle", devicejb.getString("maintenanceCycle"));
		    			devicevalue.put("producers", devicejb.getString("manufacturer"));//生产商
		    			devicevalue.put("productionDate", devicejb.getString("manufactureDate"));//生产日期
		    			String usestatus=devicejb.getString("useStatus");
		    			String str="拆除";
		    			if(usestatus.equals("0")){
		    			    str="在用";
		    			}else if(usestatus.equals("1")){
		    			    str="安装";
		    			}
		    			devicevalue.put("useStatus",str );//使用状态
		    			devicevalue.put("openStatus", ss1[devicejb.getInt("openStatus")]);//开启状态
		    			devicevalue.put("devicetype", ss[devicejb.getInt("type")]);//设备类型()
		    			devicevalue.put("operationtype",type);//0周期巡检  1灵时巡检
		    		
		    			devicevalue.put("devicesort", devicejb.getInt("inspectListOrder"));//设备在设备册的顺序    			    			
		    			JSONObject  vmp=devicejb.getJSONObject("vmp");
		    			devicevalue.put("devicenumber", vmp.getString("valveNumber"));//设备编号
		    			devicevalue.put("InstallationDate", vmp.getString("intallDate"));//安装日期
		    			devicevalue.put("deviceadds", vmp.getString("addr"));//安装地址
		    			devicevalue.put("devicelib", vmp.getString("lib"));//来自设备库
		    			devicevalue.put("place", vmp.getString("place"));//所属场所
		    			devicevalue.put("area", vmp.getString("area"));//所属片区
		    			devicevalue.put("netWork", vmp.getString("netWork"));//所属网短
		    	                devicevalue.put("deviceitem", deviceitem);
		    			String  latitude=vmp.getString("lat");
		    			if(!TextUtils.isEmpty(latitude)&&!latitude.equals("null")){
		    			devicevalue.put("latitude", vmp.getDouble("lat"));
		    			devicevalue.put("longitude", vmp.getDouble("lon"));
		    			}else{
		    			devicevalue.put("latitude",0.0);
		    			devicevalue.put("longitude", 0.0);
		    			}
		    		        String rfid=vmp.getString("rfid");
		    		         devicevalue.put("RFIDnumber", rfid);
		    			if(TextUtils.isEmpty(rfid)||rfid.equals("null")){
		    			devicevalue.put("bandingstatus", "2");
		    			}else{
		    			devicevalue.put("bandingstatus", "3");
		    			}
		    			
		    			JSONArray  tuwenjson=devicejb.getJSONArray("images");
		    			if(tuwenjson!=null&&tuwenjson.length()>0){
		    			  
		    			    for(int n=0;n<tuwenjson.length();n++){
		    				 JSONObject   tuwenjb=tuwenjson.getJSONObject(n);
		    				 ContentValues  tvalue=new ContentValues();
		    				 String isimg=tuwenjb.getString("type").equals("0")?"1":"2";
		    				 tvalue.put("othernumber", tuwenjb.getString("valveId"));
		    				 tvalue.put("isimg", isimg);
		    				 tvalue.put("waterlistid", devicelistid);
		    				 tvalue.put("type", type);
		    				 if(isimg.equals("1")){
		    				  tvalue.put("isdownload", "0");
		    				 }else{
		    				 tvalue.put("isdownload", "1");
						  tvalue.put("imgpath", tuwenjb.getString("details"));
		    				   
		    				 }
		    				 tvalue.put("imgwebname", tuwenjb.getString("details"));
		    				 System.out.println("---------isimage--------"+isimg+"---------"+tuwenjb.getString("details"));
		    				 tvalue.put("Sortnumber", tuwenjb.getString("ordre"));
		    				 tuwen.add(tvalue);
		    			    }
		    			     
		    			}
		    			
		    			
		    		        devicevo.add(devicevalue);
		    		     
		    		      publishProgress(i + 1);
		  			}
		  		    }
		  		                      dao.insertALL(devicelist, DbTableName.DEVICELIST);
		  		boolean b=    dao.insertALL(devicevo, DbTableName.DEVICEINFO);
		  		                       dao.insertALL(tuwen, DbTableName.NAVIGATION);
		  		    if(b){
		  			return "suess";
		  		    }else{
		  			return "error";
		  		    }
		  		} catch (JSONException e) {
		  		    e.printStackTrace();

		  		   return "error";
		  		
		  		}

		  	    }
		  	    return "error";

		  	}

		  	@Override
		  	protected void onPreExecute() {
		  	    server = new HttpClientServer(DeviceTaskActivity.this);
		  	 

		  	    dialog.setMax(100);
		  	    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		  	    dialog.setTitle("下载数据中.......");
		  	    dialog.setCancelable(false);
		  	    dialog.show();

		  	}

		  	@Override
		  	protected void onProgressUpdate(Integer... values) {
		  	    System.out.println("onprogress------>" + (int) ((float) total / values[0] * 100));
		  	    System.out.println("----------values---" + values[0]);
		  	    dialog.setProgress((int) ((float) values[0] / total * 100));
		  	}

		  	@Override
		  	protected void onPostExecute(String result) {

		  	    dialog.cancel();
		  	    if (TextUtils.isEmpty(result)) {
		  		Toast.makeText(DeviceTaskActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
		  		
		  	    } else if (result.equals("error")) {
		  		Toast.makeText(DeviceTaskActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
		  	    } else {
		  		Toast.makeText(DeviceTaskActivity.this, "下载成功,共下载抄表数据:" + watertotal, Toast.LENGTH_SHORT).show();
		  		downTuwen();
		  		sp.insertValue(XmlNameHelper.rounting_update_date, DateUtil.getNowDate());
		  	    }

		  	}

		      }
	
	
	
	
	
	   public String abc(String info){
			String str="";
			for(int i=0;i<8;i++){
			    str=str+info.charAt(i)+",";
			}
			return str.substring(0, str.length()-1);
		    }
	
	
	
	   // 下载图文数据
	    public void downTuwen() {
		System.out.println("-----------开始 下载图片-------------");
		if(downma==null){
		    downma=new DownloadManager(this, myHandler, dao.getDb());
		}

		List<DownloadItem> list = dao.queryNoDown();
		
		if (list == null || list.size() < 1) {
		   updateUi();
		    return;
		}
		
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setTitle("下载图文中.......");
		pd.setCancelable(false);
		pd.setButton("取消", new DialogInterface.OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			error=0;
			pd.dismiss();
			downma.stop();
			updateUi();
		    }
		});
		pd.setButton2("放弃下载", new DialogInterface.OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			error=0;
			pd.dismiss();
			downma.stop();
		     updateUi();
			return;
		    }
		});
		
		
		downma.start();
		error=0;
		pd.setMax(list.size());
		for (int i = 0; i < list.size(); i++) {
		    downma.addTask(list.get(i));
		}
		pd.show();
	    }
	    
	    Handler myHandler = new Handler() {

	  	@Override
	  	public void handleMessage(Message msg) {
	  	    if (msg.what == 0) {
	  		
	  		pd.setProgress(pd.getProgress() + 1);
	  		if (pd.getMax() == pd.getProgress()) {
	                      pd.dismiss();
	  		     Toast.makeText(DeviceTaskActivity.this, "下载图文成功", Toast.LENGTH_SHORT).show();
	  		
	  		    downma.stop();
	  		   
	  		}
	  	    } else if (msg.what == 1) {
//	  		pd.dismiss();
//	  		downma.stop();
//	  		adapter.downUpdateView(postion, waterlistid);	

	  	    } else if (msg.what == 2) {
	  		error++;
	  		
	  		if (pd.getMax() == pd.getProgress()+error) {
	  		    pd.setMessage("下载完成，共有"+error+"张图片下载失败");
	 		     Toast.makeText(DeviceTaskActivity.this, "", Toast.LENGTH_SHORT).show();
	  		    downma.stop();
	  		   
	  		}
	  	    }
	  	    super.handleMessage(msg);
	  	}

	      };
	      
	
	
	
	

	@Override
	public void onClick(View v) {
		Intent  intent=null;
		switch (v.getId()) {
		//巡检
		case R.id.device_list_go:
			intent=new Intent(DeviceTaskActivity.this, DeviceRoutingCheck.class);
			intent.putExtra("devicelistid", list.get(Integer.parseInt(v.getTag().toString())).getDeviceListId());
			startActivityForResult(intent, REQUEST_CODE_ROUTING);
			break;
		//查询
		case R.id.device_list_query:
			intent=new Intent(DeviceTaskActivity.this, DeviceQueryActivity.class);
			intent.putExtra("devicelistid", list.get(Integer.parseInt(v.getTag().toString())).getDeviceListId());
			startActivityForResult(intent, REQUEST_CODE_QUERY);
			break;
		
		//上传
		case R.id.device_list_upload:
			
			break;
		default:
			break;
		}
		
	}

	@Override
	protected void onDestroy() {
		dao.close();
		super.onDestroy();
	}

	
}
